<?php

/**
 * 重要！
 * 所有开发这个Controller的开发者
 * 必须先查看BaseMemberController内关于Multiple-Tenant的逻辑！
 * BaseMemberController::init()方法中！
 * 还有bootstarp方法的作用！
 * @author william.sun
 */

namespace app\controllers;

use app\models\Customer;
use app\models\FormClickRecord;
use Yii;
use yii\web\Response;
use app\components\BaseMemberController;
use app\components\Api;
use app\components\Loyalty;
use app\components\Log;
use app\models\Tenant;
use app\models\State;
use app\models\City;
use app\models\District;
use app\models\MemberCardMap;
use yii\web\ServerErrorHttpException;
use app\components\PerformanceLog;
use app\models\PfLog;

class MemberController extends BaseMemberController
{       
	public $enableCsrfValidation = false;
    // ---------------------------------> 昊祥科技 <---------------------------------
    // 会员中心首页
    public function actionIndexHxkj()
    {
//         if (isset($_GET['is_webform']) && $_GET['is_webform'] == 'y') {
//             $this->setOpenid($_GET['openid']);
//         }
//         $wechatInfo = $this->getWechatInfo();
//         $userInfo = $this->getUserInfo();

//         if (!isset($userInfo['code'])) {
//             $model = Tenant::find()->where(['appid' => $this->appid])->one();
//             if ($model) {
//                 $webform_url = $model->webform_url;
//             } else {
//                 throw new ServerErrorHttpException('WEBFORM URL NOT FOUND.');
//             }
//             return $this->redirect($webform_url . '&openid=' . $this->openid . '&appid=' . $this->appid . '&is_webform=y');
//         }
//         return $this->render('index', [
//             'wechatInfo' => $wechatInfo,
//             'userInfo' => $userInfo
//         ]);
        // is_webform=y表示新用户注册成功，再次跳转回来
//         $re = Loyalty::customer_delete(['code' => "18628272611"]);
//         var_dump($re);die;
        if (isset($_GET['is_webform']) && $_GET['is_webform'] == 'y') {
        	$this->setOpenid($_GET['openid']);
        }
        
        $userInfo = $this->getUserInfo();
        
        //记录注册行为
        $formClickRecord = FormClickRecord::find()->where(['openid' => $this->openid, 'identifier' => $this->getIdentifier(), 'status' => 1])->one();
        if (isset($userInfo['code']) && !empty($formClickRecord)){
        	$formClickRecord->status = 2;
        	$formClickRecord->save();
        }        
        $sign = \app\models\ApiTicket::getsignature('p2RmrtxeU9xuLfXoEbFJFPLQf4kI');
        // 如果没有用户信息，为新用户，跳转到Webform
        if (!isset($userInfo['code'])) {
        	$webform_url = Tenant::find()->select('webform_url')->where(['appid' => $this->appid])->scalar();
        	if (empty($webform_url)) {
        		throw new ServerErrorHttpException('WEBFORM URL NOT FOUND.');
        	} else {
        		// 记录点击行为
        		if (empty($formClickRecord)) {
        			$formClickRecord = new FormClickRecord();
        		}
        
        		$formClickRecord->openid = $this->openid;
        		$formClickRecord->identifier = $this->getIdentifier();
        		$formClickRecord->clicks++;
        		$formClickRecord->status = 1;
        		$formClickRecord->redirect_url = $webform_url;
        		$formClickRecord->save();                		
//         		return $this->redirect($webform_url . '&openid=' . $this->openid . '&appid=' . $this->appid . '&is_webform=y');
        		return $this->render('new_index', [
        				'openid' => $this->openid,
        				'appid' => $this->appid,
        				'sign' => $sign,
        				]);
        	}
        }
        //         $this->bp($userInfo);
        $cardMap = MemberCardMap::find()->where(['openid' => $userInfo['wechat_openid']])->one();
        //         $this->bp($cardMap);
        return $this->render('index', [
        		'userInfo' => $userInfo,
        		'sign' => $sign,
        		'cardMap' => $cardMap,
        ]);
    }

    public function actionViewHxkj()
    {
    	$userInfo = $this->getUserInfo();
    	$state = State::findOne((int)$userInfo['state']);
    	$city = City::findOne((int)$userInfo['city']);
    	$district = District::findOne((int)$userInfo['district']);
    	 
    	if ($userInfo['state'] == '01') {
    		$address = '香港特别行政区';
    	} elseif ($userInfo['state'] == '02') {
    		$address = '澳门特别行政区';
    	} else {
    		if (!empty($state) && !empty($city) && !empty($district)) {
    			$address = $state['name'] . $city['name'] . $district['name'];
    		} else {
    			$address = '';
    		}
    	}
    	 
    	// 直辖市
    	if ($state['name'] == '北京市' || $state['name'] == '天津市' || $state['name'] == '上海市' || $state['name'] == '重庆市') {
    		$address = $state['name'] . $district['name'];
    	}
    	 
    	if (empty($userInfo['email']) || empty($userInfo['first_name']) || empty($userInfo['birth_mm']) || empty($userInfo['state']) || empty($userInfo['agegroup'])) {
    		$isComplete = true;
    	} else {
    		$isComplete = false;
    	}
    	 
    	return $this->render('view', [
    			'userInfo' => $userInfo,
    			'isComplete' => $isComplete,
    			'address' => $address,
    			]);
    }
    
    // 个人资料补充
    public function actionProfileHxkj()
    {
         if (Yii::$app->request->isPost) {
            $data = Yii::$app->request->post();
            $data = array_filter($data);
            unset($data['_csrf']);
            unset($data['mobile']);
            unset($data['cmbProvince']);
            unset($data['cmbCity']);
            unset($data['cmbArea']);
            // 修改年份以用来区别
            $data['birth_yyyy'] = '2018';
            Loyalty::customer_update($data);
            $userInfo = Loyalty::customer_get(['code' => $data['code']]);
            $this->setUserInfo($userInfo);
            $this->redirect(['member/index']);
        } else {
            $userInfo = $this->getUserInfo();
        }
        
        $state = State::findOne($userInfo['state']);
        $city = City::findOne($userInfo['city']);
        $district = District::findOne($userInfo['district']);

        if (empty($userInfo['email']) || empty($userInfo['last_name']) || empty($userInfo['gender']) || empty($userInfo['birthday'])) {
            $isComplete = true;
        } else {
            $isComplete = false;
        }

        return $this->render('profile', [
            'userInfo' => $userInfo,
            'isComplete' => $isComplete,
            'state' => $state,
            'city' => $city,
            'district' => $district,
        ]);
    }

    // 会员卡资料
    public function actionCardDetailHxkj()
    {
        return $this->render('card-detail');
    }

    // 积分列表
    public function actionPointsDetailHxkj()
    {
        $re = Loyalty::customer_tnx_detail(['campaign_id' => 1, 'code' => '0601000100000491079', 'pagesize' => '1', 'pageno' => '1']);
        if ($re['status'] == "success"){
            $points = $re['total'];
        }else{
            $points = 0;
        }
        return $this->render('points-detail', [
            'points' => $points,
        ]);
    }
    // ---------------------------------> 昊祥科技 <---------------------------------

    
    // ---------------------------------> 轩客会 <---------------------------------
    // 会员中心首页
    public function actionIndexWinshare()
    {
        // $openid = 'o0TqJuMsPSvBniRAyicU67FRGyO0'; // william
        if (isset($_GET['is_webform']) && $_GET['is_webform'] == 'y') {
            $this->setOpenid($_GET['openid']);
        }

        $userInfo = $this->getUserInfo();
        // 跳转到Webform
        if (!isset($userInfo['code'])) {
            $model = Tenant::find()->where(['appid' => $this->appid])->one();
            if ($model) {
                $webform_url = $model->webform_url;
            } else {
                throw new ServerErrorHttpException('WEBFORM URL NOT FOUND.');
            }
            return $this->redirect($webform_url . '&openid=' . $this->openid . '&appid=' . $this->appid . '&is_webform=y');
        }

        return $this->render('index', [
            'userInfo' => $userInfo,
        ]);
    }

    // 个人资料补充
    public function actionProfileWinshare()
    {
        if (Yii::$app->request->isPost) {
            $data = Yii::$app->request->post();
            $data = array_filter($data);

            // 其实Loyalty的birthday更新不了是因为没有这个，birthday是由birth_yyyy/birth_mm/birth_dd拼成的
            $birthday = $data['birthday'];
            $y = substr($birthday, 0, 4);
            $m = substr($birthday, 5, 2);
            $d = substr($birthday, 8, 2);
            $data['birth_yyyy'] = $y;
            $data['birth_mm'] = $m;
            $data['birth_dd'] = $d; 
            unset($data['_csrf']);
            unset($data['birthday']);
            Loyalty::customer_update($data);
            $userInfo = Loyalty::customer_get(['code' => $data['code']]);
            $this->setUserInfo($userInfo);
            $this->redirect(['member/index']);
        } else {
            $userInfo = $this->getUserInfo();
        }

        if (isset($userInfo['email']) && isset($userInfo['last_name']) && isset($userInfo['gender']) && isset($userInfo['birthday'])) {
            $isComplete = true;
        } else {
            $isComplete = false;
        }

        return $this->render('profile', [
            'userInfo' => $userInfo,
            'isComplete' => $isComplete,
        ]);
    }

    // 优惠券列表
    public function actionCouponsWinshare()
    {
        $userInfo = $this->getUserInfo();

        $data = [
            'campaign_id' => 1, //目前只能为1
            'code' => $userInfo['code'],
        ];

        // 获取所有的优惠券
        $re = Loyalty::coupon_list($data);
        if ($re['status'] == 'success') {
            $coupons = $re['result'];
            $groupids = [];
            foreach ($coupons as $k => $v) {
                $groupids[] = $v['coupongroup_id'];
            }
            // 取出不重复的coupongroup_id，并获取这个coupongroup的详细信息
            $unique_groupids = array_unique($groupids);
            $coupon_details = [];
            foreach ($unique_groupids as $v) {
                $re = Loyalty::coupon_detail(['campaign_id' => 1, 'coupongroup_id' => $v]);
                if ($re['status'] == 'success') {
                    $detail = $re['result'];
                    $coupon_details[$v] = $detail;
                }
            }
            // 把详细信息返回给原优惠券数组
            foreach ($coupons as $k => $v) {
                $coupons[$k]['detail'] = $coupon_details[$v['coupongroup_id']];
            }
        } else {
            $coupons = false;
        }
        
        return $this->render('coupons', [
            'coupons' => $coupons
        ]);
    }

    // 会员卡详情
    public function actionCardDetailWinshare()
    {
        return $this->render('card-detail');
    }

    // 积分入口
    public function actionPointsWinshare()
    {
        return $this->render('points');
    }
    // ---------------------------------> 轩客会 <---------------------------------

    // ---------------------------------> MOMO <---------------------------------
    // 会员中心首页
    public function actionIndexMomo()
    {
    	// is_webform=y表示新用户注册成功，再次跳转回来
    	if (isset($_GET['is_webform']) && $_GET['is_webform'] == 'y') {
    		$this->setOpenid($_GET['openid']);
    	}
    
    	$userInfo = $this->getUserInfo();
    
    	// 如果没有用户信息，为新用户，跳转到Webform
    	if (!isset($userInfo['code'])) {
    		$model = new Customer();
    		$webform_url = Tenant::find()->select('webform_url')->where(['appid' => $this->appid])->scalar();
    		if (empty($webform_url)) {
    			throw new ServerErrorHttpException('WEBFORM URL NOT FOUND.');
    		} else {
    			return $this->render('create', [
    					'model' => $model,
    					'openid' => $this->openid,
    					'appid' => $this->appid,
    					]);
    			// return $this->redirect($webform_url . '&openid=' . $this->openid . '&appid=' . $this->appid . '&is_webform=y');
    		}
    	}
    	return $this->render('index', [
    			'userInfo' => $userInfo,
    			]);
    }
    
    // 异步检查用户
    public function actionCustomerSaveMomo()
    {
    	if (Yii::$app->request->isPost) {
    		// 获取用户信息
    		$last_name = Yii::$app->request->post('last_name');
    		$mobile = Yii::$app->request->post('mobile');
    		$gender = Yii::$app->request->post('gender');
    		$email = Yii::$app->request->post('email');
    		$openid = Yii::$app->request->post('openid');
    		$birthday = Yii::$app->request->post('birthday');
    		// 查询该用户是否存在
    		$search_re = Loyalty::customer_search(['mobile' => $mobile]);
    		//验证手机号唯一性
    		if ($search_re['status'] == 'error') {
    			// 不存在用户新建
    			return json_encode(['type' => 'new']);
    		} elseif ($search_re['status'] == 'success') {
    			//判断老用户openid是否存在，防止重复更新openid
    			$customers = $search_re['result']['customers'];
    			$wechat_openid = array_column($customers, 'wechat_openid');
    			if (empty($wechat_openid[0])){
    				// 已存在用户直接更新
    				if (!empty($birthday)) {
    					$y = substr($birthday, 0, 4);
    					$m = substr($birthday, 5, 2);
    					$d = substr($birthday, 8, 2);
    					$data['birth_yyyy'] = $y;
    					$data['birth_mm'] = $m;
    					$data['birth_dd'] = $d;
    				}
    
    				$customer = current($search_re['result']['customers']);
    				$data = [
    				'code' => $customer['code'],
    				'last_name' => $last_name,
    				'mobile' => $mobile,
    				'gender' => $gender,
    				'email' => empty($email) ? '' : $email,
    				'wechat_openid' => $openid,
    				];
    				$save_re = Loyalty::customer_update($data);
    				if ($save_re['status'] == 'success') {
    					$this->setOpenid($openid);
    					return json_encode(['type' => 'old']);
    				}
    			} else {
    				return json_encode(['type' => 'error']);
    			}
    		}
    	}
    }
    
    public function actionViewMomo()
    {
    	$userInfo = $this->getUserInfo();
    
    	if (empty($userInfo['email']) || empty($userInfo['last_name']) || empty($userInfo['gender']) || empty($userInfo['birthday'])) {
    		$isComplete = true;
    	} else {
    		$isComplete = false;
    	}
    
    	return $this->render('view', [
    			'userInfo' => $userInfo,
    			'isComplete' => $isComplete,
    			]);
    }
    
    // momo个人资料补充
    public function actionProfileMomo()
    {
    	if (Yii::$app->request->isPost) {
    		$data = Yii::$app->request->post();
    		$data = array_filter($data);
    
    		// 其实Loyalty的birthday更新不了是因为没有这个，birthday是由birth_yyyy/birth_mm/birth_dd拼成的
    		$birthday = $data['birthday'];
    		$y = substr($birthday, 0, 4);
    		$m = substr($birthday, 5, 2);
    		$d = substr($birthday, 8, 2);
    		$data['birth_yyyy'] = $y;
    		$data['birth_mm'] = $m;
    		$data['birth_dd'] = $d;
    		unset($data['_csrf']);
    		unset($data['birthday']);
    		$data['mobile'] = 86 . $data['mobile'];
    
    		Loyalty::customer_update($data);
    		$userInfo = Loyalty::customer_get(['code' => $data['code']]);
    		$this->setUserInfo($userInfo);
    		$this->redirect(['member/index']);
    	} else {
    		$userInfo = $this->getUserInfo();
    	}
    
    	if (empty($userInfo['email']) || empty($userInfo['last_name']) || empty($userInfo['gender']) || empty($userInfo['birthday'])) {
    		$isComplete = true;
    	} else {
    		$isComplete = false;
    	}
    
    	return $this->render('profile', [
    			'userInfo' => $userInfo,
    			'isComplete' => $isComplete,
    			]);
    }
    
    // 会员卡详情
    public function actionCardDetailMomo()
    {
    	$userInfo = $this->getUserInfo();
    	return $this->render('card-detail', ['userInfo' => $userInfo]);
    }
    
    // 积分列表
    public function actionPointsDetailMomo()
    {
    	$userInfo = $this->getUserInfo();
    	$re = Loyalty::customer_tnx_detail(['campaign_id' => 2, 'code' => $userInfo['code'], 'pagesize' => '10', 'pageno' => '1']);
    	$points = $re['transactions'];
    	return $this->render('points-detail', [
    			'points' => $points,
    			]);
    }
    // ---------------------------------> MOMO <---------------------------------


    //----------------------------------> Jebsen <--------------------------------
    // 会员中心首页
    public function actionIndexJebsen()
    {
//     	$pflog_id = Yii::$app->session->get('pflog_id');
        $userInfo = $this->getUserInfo();

        //记录注册行为
        $formClickRecord = FormClickRecord::find()->where(['openid' => $this->openid, 'identifier' => $this->getIdentifier(), 'status' => 1])->one();
        if (isset($userInfo['code']) && !empty($formClickRecord)){
            $formClickRecord->status = 2;
            $formClickRecord->save();
        }

        // 如果没有用户信息，为新用户，跳转到Webform
        if (!isset($userInfo['code'])) {
            $webform_url = Tenant::find()->select('webform_url')->where(['appid' => $this->appid])->scalar();
            if (empty($webform_url)) {
                throw new ServerErrorHttpException('WEBFORM URL NOT FOUND.');
            } else {
                // 记录点击行为
                if (empty($formClickRecord)) {
                    $formClickRecord = new FormClickRecord();
                }
                
                $formClickRecord->openid = $this->openid;
                $formClickRecord->identifier = $this->getIdentifier();
                $formClickRecord->clicks++;
                $formClickRecord->status = 1;
                $formClickRecord->redirect_url = $webform_url;
                $formClickRecord->save();
				
                // performance log
// 				$pflog = PfLog::findOne($pflog_id);
// 				if ($pflog) {
// 					$pflog->end();
// 				}
// 				Yii::$app->session->remove('pflog_id');
				
                return $this->redirect($webform_url . '&openid=' . $this->openid . '&appid=' . $this->appid . '&is_webform=y');
            }
        }
        
        // performance log
//         $pflog = PfLog::findOne($pflog_id);
//         if ($pflog) {
//         	$pflog->end('existing');
//         }
//         Yii::$app->session->remove('pflog_id');
        
        return $this->render('index', [
            'userInfo' => $userInfo,
        ]);
    }

    public function actionViewJebsen()
    {
    	$userInfo = $this->getUserInfo();
//     	$this->bp($userInfo);
    	$state = State::findOne((int)$userInfo['state']);
    	$city = City::findOne((int)$userInfo['city']);
    	$district = District::findOne((int)$userInfo['district']);
    	
    	if ($userInfo['state'] == '01') {
    		$address = '香港特别行政区';
    	} elseif ($userInfo['state'] == '02') {
    		$address = '澳门特别行政区';
    	} else {
    		if (!empty($state) && !empty($city) && !empty($district)) {
    			$address = $state['name'] . $city['name'] . $district['name'];
    		} else {
    			$address = '';
    		}
    	}
    	
    	// 直辖市
    	if ($state['name'] == '北京市' || $state['name'] == '天津市' || $state['name'] == '上海市' || $state['name'] == '重庆市') {
    		$address = $state['name'] . $district['name'];
    	}
    	
    	if (empty($userInfo['email']) || empty($userInfo['first_name']) || empty($userInfo['birth_mm']) || empty($userInfo['state']) || empty($userInfo['agegroup'])) {
    		$isComplete = true;
    	} else {
    		$isComplete = false;
    	}
    	
    	if ($userInfo['gender'] == 'ns') {
    		$userInfo['gender'] = '女士';
    	}
    	
    	return $this->render('view', [
    			'userInfo' => $userInfo,
    			'isComplete' => $isComplete,
    			'address' => $address,
    	]);
    }

    // jebsen个人资料补充
    public function actionProfileJebsen()
    {
        if (Yii::$app->request->isPost) {
            $data = Yii::$app->request->post();
            $data = array_filter($data);
            unset($data['_csrf']);
            unset($data['mobile']);
            unset($data['cmbProvince']);
            unset($data['cmbCity']);
            unset($data['cmbArea']);
            // 修改年份以用来区别
            $data['birth_yyyy'] = '2018';
//             $this->bp($data);
            Loyalty::customer_update($data);
            $userInfo = Loyalty::customer_get(['code' => $data['code']]);
            $this->setUserInfo($userInfo);
            $this->redirect(['member/index']);
        } else {
            $userInfo = $this->getUserInfo();
        }
        
        $state = State::findOne($userInfo['state']);
        $city = City::findOne($userInfo['city']);
        $district = District::findOne($userInfo['district']);

        if (empty($userInfo['email']) || empty($userInfo['last_name']) || empty($userInfo['gender']) || empty($userInfo['birthday'])) {
            $isComplete = true;
        } else {
            $isComplete = false;
        }

        return $this->render('profile', [
            'userInfo' => $userInfo,
            'isComplete' => $isComplete,
            'state' => $state,
            'city' => $city,
            'district' => $district,
        ]);
    }
    
    public function actionCouponJebsen()
    {
    	$userInfo = $this->getUserInfo();
    	$re = Loyalty::get_coupon_codes(['code' => $userInfo['code']]);
    	if ($re['status'] == 'success') {
    		$coupon_codes = $this->buildCouponInfo($re['coupon_codes']);
    		$coupons = $coupon_codes;
    	} else {
    		$coupons = '';
    	}
    	
//     	header("Content-type: text/html; charset=utf-8");
// 		$this->bp($couopns);
    	 
    	return $this->render('coupon', [
    			'coupons' => $coupons,
    			'userInfo' => $userInfo,
    			'redirect_url' => isset($_GET['redirect_url']) ? urldecode($_GET['redirect_url']) : '',
    			'redirect_name' => isset($_GET['redirect_name']) ? $_GET['redirect_name'] : '',
    	]);
    }
    
    public function actionRedeemCouponJebsen()
    {
    	if (Yii::$app->request->isPost && Yii::$app->request->isAjax) {
    		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    		$datas = Yii::$app->request->post();
    		$re = Loyalty::coupon_redeem(['coupon_code' => $datas['coupon_code'], 'redeem_password' => $datas['redeem_password']]);
    		return $re;
    	} else {
    		return ['status' => 'error'];
    	}
    }

    // 会员卡详情
    public function actionCardDetailJebsen()
    {
        return $this->render('card-detail');
    }

    // 积分列表
    public function actionPointsDetailJebsen()
    {
        $userInfo = $this->getUserInfo();
        $re = Loyalty::customer_tnx_detail(['campaign_id' => 3, 'code' => $userInfo['code'], 'pagesize' => '10', 'pageno' => '1']);
        $points = $re['transactions'];
        return $this->render('points-detail', [
            'points' => $points,
        ]);
    }
    //----------------------------------> Jebsen <--------------------------------

    // 积分明细
    // TODO:campaign_id没有
    public function actionPoints_detail()
    {   
        // $userInfo = $this->getUserInfo();
        // $code = $userInfo['code'];
        // $pagesize = 20;   

        // $data = [
        //     'code' => $code,
        //     'campaign_id' => 1,
        //     'pagesize' => $pagesize,
        //     'pageno' => Yii::$app->request->post('page', 1),
        // ];
        // $points_detail = Loyalty::customer_tnx_detail($data);

        // if (Yii::$app->request->isPost) {
        //     echo json_encode($points_detail['transactions']);
        // } else {
        //     return $this->render('points_detail', ['transactions' => $points_detail['transactions'], 'code' => $code]);
        // }
        return $this->render('points_detail_origin');
    }

    // 交易记录
    public function actionTransactions()
    {  
        $userInfo = $this->getUserInfo();
        $code = $userInfo['code'];
        $transactions = [
            ['serialNo'=>'12324522495', 
                'store'=>'成都世纪城店', 
                'date'=>'2017/08/06',
                'type'=>'1', 
                'goods'=>[
                    [
                     'points'=>'35', 
                     'book'=>'Javascript 从入门到跳楼', 
                     'quantity'=>'3',
                     'price'=>'35'
                    ]
                 ]
            ],
            ['serialNo'=>'12324522494', 
                'store'=>'成都世纪城店', 
                'date'=>'2017/08/06',
                'type'=>'1', 
                'goods'=>[
                    [
                     'points'=>'35', 
                     'book'=>'Javascript 从入门到跳楼', 
                     'quantity'=>'2',
                     'price'=>'35',
                    ],
                    [
                     'points'=>'56', 
                     'book'=>'Javascript 从入门到放弃', 
                     'quantity'=>'2',
                     'price'=>'25',
                    ] 
                ]   
            ],
                
           
            ['serialNo'=>'12324522490', 
                'store'=>'成都世纪城店', 
                'date'=>'2017/08/06',
                'type'=>'1', 
                'goods'=>[
                    [
                     'points'=>'35', 
                     'book'=>'Javascript 从入门到跳楼', 
                     'quantity'=>'3',
                     'price'=>'35'
                    ]
                 ]
            ]
        ];

        return $this->render('transactions', ['transactions'=>$transactions]);
    }
    
    
    //----------------------------------> New Jebsen <--------------------------------
    
    // 会员中心首页
    public function actionIndexJselect()
    {
    	$userInfo = $this->getUserInfo();
//     	$this->bp($userInfo);exit;
//     	Log::debug('UserInfo',$userInfo);
    	//记录注册行为
    	$formClickRecord = FormClickRecord::find()->where(['openid' => $this->openid, 'identifier' => $this->getIdentifier(), 'status' => 1])->one();
    	if (isset($userInfo['code']) && !empty($formClickRecord)){
    		$formClickRecord->status = 2;
    		$formClickRecord->save();
    	}
    	// 原生会员卡暂时注释
    	// $sign = \app\models\ApiTicket::getsignature('p2RmrtxScDyRALt10AGgpKmzaNjk');
    	// 如果没有用户信息，为新用户，跳转到Webform
    	if (!isset($userInfo['code'])) {
    		$webform_url = Tenant::find()->select('webform_url')->where(['appid' => $this->appid])->scalar();
    		if (empty($webform_url)) {
    			throw new ServerErrorHttpException('WEBFORM URL NOT FOUND.');
    		} else {
    			// 记录点击行为
    			if (empty($formClickRecord)) {
    				$formClickRecord = new FormClickRecord();
    			}
    
    			$formClickRecord->openid = $this->openid;
    			$formClickRecord->identifier = $this->getIdentifier();
    			$formClickRecord->clicks++;
    			$formClickRecord->status = 1;
    			$formClickRecord->redirect_url = $webform_url;
    			$formClickRecord->save();

    			// get origin card
//     			return $this->render('get-card', [
//     					'openid' => $this->openid,
//     					'appid' => $this->appid,
//     					'sign' => $sign,
//     			]);

    			// redirect to webform
    			return $this->redirect($webform_url . '&openid=' . $this->openid . '&appid=' . $this->appid . '&is_webform=y');
    		}
    	}
    	
    	// 原生会员卡暂时注释
    	// $cardMap = MemberCardMap::find()->where(['openid' => $userInfo['wechat_openid']])->one();
    	
        return $this->render('index', [
        		'userInfo' => $userInfo,
//         		原生会员卡暂时注释
//         		'sign' => $sign,
//         		原生会员卡暂时注释
//         		'cardMap' => $cardMap,
        ]);
    }
    
    public function actionViewJselect()
    {
    	$userInfo = $this->getUserInfo();
    	$state = State::findOne((int)$userInfo['state']);
    	$city = City::findOne((int)$userInfo['city']);
    	$district = District::findOne((int)$userInfo['district']);
    	 
    	if ($userInfo['state'] == '01') {
    		$address = '香港特别行政区';
    	} elseif ($userInfo['state'] == '02') {
    		$address = '澳门特别行政区';
    	} else {
    		if (!empty($state) && !empty($city) && !empty($district)) {
    			$address = $state['name'] . $city['name'] . $district['name'];
    		} else {
    			$address = '';
    		}
    	}
    	 
    	// 直辖市
    	if ($state['name'] == '北京市' || $state['name'] == '天津市' || $state['name'] == '上海市' || $state['name'] == '重庆市') {
    		$address = $state['name'] . $district['name'];
    	}
    	 
    	if (empty($userInfo['email']) || empty($userInfo['first_name']) || empty($userInfo['birth_mm']) || empty($userInfo['state']) || empty($userInfo['agegroup'])) {
    		$isComplete = true;
    	} else {
    		$isComplete = false;
    	}
    	 
    	return $this->render('view', [
    			'userInfo' => $userInfo,
    			'isComplete' => $isComplete,
    			'address' => $address,
    	]);
    }
    
    // jebsen个人资料补充
    public function actionProfileJselect()
    {
    	if (Yii::$app->request->isPost) {
    		$data = Yii::$app->request->post();
    		$data = array_filter($data);
    		unset($data['_csrf']);
    		unset($data['mobile']);
    		unset($data['cmbProvince']);
    		unset($data['cmbCity']);
    		unset($data['cmbArea']);
    		// 修改年份以用来区别
    		$data['birth_yyyy'] = '2018';
    		Loyalty::customer_update($data);
    		$userInfo = Loyalty::customer_get(['code' => $data['code']]);
    		$this->setUserInfo($userInfo);
    		$this->redirect(['member/index']);
    	} else {
    		$userInfo = $this->getUserInfo();
    	}
    
    	$state = State::findOne($userInfo['state']);
    	$city = City::findOne($userInfo['city']);
    	$district = District::findOne($userInfo['district']);
    
    	if (empty($userInfo['email']) || empty($userInfo['last_name']) || empty($userInfo['gender']) || empty($userInfo['birthday'])) {
    		$isComplete = true;
    	} else {
    		$isComplete = false;
    	}
    
    	return $this->render('profile', [
    			'userInfo' => $userInfo,
    			'isComplete' => $isComplete,
    			'state' => $state,
    			'city' => $city,
    			'district' => $district,
    	]);
    }
    
    // 会员卡详情
    public function actionCardDetailJselect()
    {
    	return $this->render('card-detail');
    }
    
    // 积分列表
    public function actionPointsDetailJselect()
    {
    	$userInfo = $this->getUserInfo();
    	$re = Loyalty::customer_tnx_detail(['campaign_id' => 3, 'code' => $userInfo['code'], 'pagesize' => '10', 'pageno' => '1']);
    	$points = $re['transactions'];
    	
    	return $this->render('points-detail', [
    			'points' => $points,
    	]);
    }
    
    //优惠券列表
	public function actionCouponJselect()
    {
    	$userInfo = $this->getUserInfo();    	
    	$re = Loyalty::get_coupon_codes(['code' => $userInfo['code']]);
    	if ($re['status'] == 'success') {
    		$coupon_codes = $this->buildCouponInfo($re['coupon_codes']);
    		$coupons = $coupon_codes;
    	} else {
    		$coupons = '';
    	}

//     	header("Content-type: text/html; charset=utf-8");
// 		$this->bp($couopns);
    	
    	return $this->render('coupon', [
    			'coupons' => $coupons,
    			'userInfo' => $userInfo,
    			'redirect_url' => isset($_GET['redirect_url']) ? urldecode($_GET['redirect_url']) : '',
    			'redirect_name' => isset($_GET['redirect_name']) ? $_GET['redirect_name'] : '',
    	]);
    }
    
    /**
     * redeem coupon ajax
     */
    public function actionRedeemCouponJselect()
    {
    	if (Yii::$app->request->isPost && Yii::$app->request->isAjax) {
    		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    		$datas = Yii::$app->request->post();
    		$re = Loyalty::coupon_redeem(['coupon_code' => $datas['coupon_code'], 'redeem_password' => $datas['redeem_password']]);
    		return $re;
    	} else {
    		return ['status' => 'error'];
    	}
    }
    //----------------------------------> New Jebsen <--------------------------------
    /**
     * build coupon info 
     * @param array $coupon_codes
     */
    private function buildCouponInfo($coupon_codes)
    {
    	$re = Loyalty::list_coupon([]);
    	
    	foreach ($coupon_codes as $k => $v) {
    		// build coupon barcode
    		foreach ($re['coupon_list'] as $key => $value) {
    			if ($v['coupon_id'] == $value['coupon_id']) {
    				$coupon_codes[$k]['coupon_info']['barcode_pattern'] = isset($value['coupon']['barcode_pattern']) ? $value['coupon']['barcode_pattern'] : '';
    			}
    		}
    		
    		// build more coupon infomation by coupon name
    		switch ($v['coupon_info']['name']) {
    			case 'Artistic&co 面部产品体验券':
    				$coupon_codes[$k]['coupon_info']['coupon_type'] = 'ty';
    				$coupon_codes[$k]['coupon_info']['redeem_content'] = '核 销';
    				break;
    			case '美肤疗程':
    				$coupon_codes[$k]['coupon_info']['coupon_type'] = 'ty';
    				$coupon_codes[$k]['coupon_info']['redeem_content'] = '核 销';
    				break;
    			case '彩色手工面条':
    				$coupon_codes[$k]['coupon_info']['coupon_type'] = 'ty';
    				$coupon_codes[$k]['coupon_info']['redeem_content'] = '核 销';
    				break;
    			case '￥100':
    				$coupon_codes[$k]['coupon_info']['coupon_type'] = 'cash';
    				$coupon_codes[$k]['coupon_info']['redeem_content'] = '使 用';
    				break;
    			case '九折券':
    				$coupon_codes[$k]['coupon_info']['coupon_type'] = 'discount';
    				$coupon_codes[$k]['coupon_info']['redeem_content'] = '使 用';
    				break;
    			case '帆布袋':
    				$coupon_codes[$k]['coupon_info']['coupon_type'] = 'text';
    				$coupon_codes[$k]['coupon_info']['redeem_content'] = '核 销';
    				break;
    			case '手工Ciabatta恰巴塔面包券':
    				$coupon_codes[$k]['coupon_info']['coupon_type'] = 'text';
    				$coupon_codes[$k]['coupon_info']['redeem_content'] = '核 销';
    				$coupon_codes[$k]['enddate'] = '2018-09-21 23:59:59';
    				break;
    			case '姐妹淘活动抵用券':
    				$coupon_codes[$k]['coupon_info']['coupon_type'] = 'cash';
    				$coupon_codes[$k]['coupon_info']['redeem_content'] = '核 销';
    				$coupon_codes[$k]['coupon_info']['barcode_pattern'] = ['pattern_type' => 'fixed', 'fixed_value' => $coupon_codes[$k]['coupon_code']];
    				if ($coupon_codes[$k]['enddate'] == '0000-00-00 00:00:00' || $coupon_codes[$k]['enddate'] == '2018-10-31 23:59:59') {
    					$coupon_codes[$k]['enddate'] = '2018-10-31 23:59:59';
    				}
//     				$coupon_codes[$k]['enddate'] = '2018-10-31 23:59:59';
    				break;
    			default:
    				$coupon_codes[$k]['coupon_info']['coupon_type'] = 'text';
    				$coupon_codes[$k]['coupon_info']['redeem_content'] = '核 销';
    				break;
    		}
    	}
    	
    	return $coupon_codes;
    }
}
